package com.temp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.temp.entity.SystemSetting;
import com.temp.mapper.SystemSettingMapper;
import com.temp.service.SystemSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Optional;

@Service
public class SystemSettingServiceImpl extends ServiceImpl<SystemSettingMapper, SystemSetting> implements SystemSettingService {

    @Autowired
    private SystemSettingMapper settingMapper;

    @Override
    public <T> Optional<T> getSettingValue(String key, Class<T> type) {
        SystemSetting systemSetting = settingMapper.selectOne(Wrappers.<SystemSetting>lambdaQuery().eq(SystemSetting::getSettingKey, key));
        // 2. 如果查询结果为空，返回Optional.empty()
        if (systemSetting == null) {
            return Optional.empty();
        }
        // 3. 尝试解析设置值
        try {
            T parsedValue = parseValue(
                    systemSetting.getSettingValue(),
                    systemSetting.getDataType(),
                    type
            );
            return Optional.ofNullable(parsedValue);
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    // 解析值到指定类型
    private <T> T parseValue(String value, String dataType, Class<T> type) {
        try {
            if ("number".equals(dataType) && type == BigDecimal.class) {
                return type.cast(new BigDecimal(value));
            } else if ("boolean".equals(dataType) && type == Boolean.class) {
                return type.cast(Boolean.parseBoolean(value));
            } else if ("json".equals(dataType) && type != String.class) {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(value, type);
            }
            return type.cast(value);
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to parse setting value", e);
        }
    }
}
